<template>
  <div class="view-article-container">
    <div class="bg-container">
      <div class="bg-dot"></div>
      <div class="bg-dot dot-2"></div>
      <div class="bg-dot dot-3"></div>
    </div>
    <div class="article-info card-container">
      <div class="info-left">
        <h2 class="section-title">{{ article.title }}</h2>
        <div class="article-meta">
          <span class="article-author">
            <i class="el-icon-user"></i> {{ author.nickname }}
          </span>
          <span class="article-date">
            <i class="el-icon-date"></i> {{ formatDate(article.publishTime) }}
          </span>
          <span class="article-views">
            <i class="el-icon-view"></i> {{ article.viewCount }}
          </span>
          <span class="article-followers">
            <i class="el-icon-star-on"></i> {{ author.followerCount || 0 }} 粉丝
          </span>
        </div>
        <div class="article-introduction">{{ article.introduction }}</div>
        <div class="article-tags">
          <span class="tag" v-for="tag in article.tag.split(',')" :key="tag">{{
            tag
          }}</span>
        </div>
      </div>
      <div class="info-right">
        <img
          :src="
            author.avatar
              ? `data:image/jpeg;base64,${author.avatar}`
              : 'https://picsum.photos/200/200?random=4'
          "
          alt="用户头像"
          class="user-avatar-small"
        />
        <div v-if="isAuthor" class="edit-button">
          <el-button type="warning" size="small" @click="editArticle"
            >修改文章</el-button
          >
        </div>
        <div v-else>
          <el-button
            :type="isFollowing ? 'danger' : 'primary'"
            :loading="loading"
            size="small"
            @click="toggleFollow"
          >
            {{ isFollowing ? "取消关注" : "关注作者" }}
          </el-button>
        </div>
      </div>
    </div>
    <div class="article-content">
      <v-md-preview :text="articleContent"></v-md-preview>
    </div>
  </div>
</template>

<script>
import VueMarkdownPreview from "@kangc/v-md-editor/lib/preview";
import "@kangc/v-md-editor/lib/style/preview.css";
import vuepressTheme from "@kangc/v-md-editor/lib/theme/vuepress.js";
import "@kangc/v-md-editor/lib/theme/style/vuepress.css";

VueMarkdownPreview.use(vuepressTheme);

export default {
  components: {
    "v-md-preview": VueMarkdownPreview,
  },
  data() {
    return {
      article: {},
      author: {},
      articleContent: "",
      isAuthor: false,
      isFollowing: false,
      loading: false,
    };
  },
  async mounted() {
    await this.fetchArticleData();
  },
  methods: {
    async fetchArticleData() {
      try {
        const articleId = this.$route.params.id;
        // 获取文章详情
        const articleResponse = await this.$axios.get(
          `/article/detail/${articleId}`
        );
        if (articleResponse.data.code !== 200) {
          this.$message.error("文章不存在");
          return this.$router.back();
        }

        this.article = articleResponse.data.data;

        // 获取作者信息
        const authorResponse = await this.$axios.get(
          `/user/info/${this.article.userId}`
        );
        if (authorResponse.data.code === 200) {
          this.author = authorResponse.data.data;
        }

        // 获取文章内容
        const markdownResponse = await this.$axios.get(this.article.content);
        this.articleContent = markdownResponse.data;

        // 增加文章阅读量
        await this.$axios.post(`/article/increaseViewCount/${articleId}`);

        // 判断当前用户是否为文章的作者
        this.isAuthor = this.$store.state.user.id === this.article.userId;

        if (!this.isAuthor && this.$store.state.user.id) {
          // 如果不是作者且用户已登录，检查是否已关注作者
          const followingResponse = await this.$axios.get(
            `/following/list/${this.$store.state.user.id}`
          );
          if (followingResponse.data.code === 200) {
            const followingIds = followingResponse.data.data.map(
              (following) => following.followingUserId
            );
            this.isFollowing = followingIds.includes(this.article.userId);
          }
        }
      } catch (error) {
        console.error("文章查看失败", error);
        this.$message.error("加载文章失败");
      }
    },
    formatDate(timestamp) {
      return new Date(timestamp).toLocaleDateString();
    },
    async toggleFollow() {
      if (this.loading) return;
      this.loading = true;

      try {
        const userId = this.$store.state.user.id;
        const followingUserId = this.article.userId;

        if (!userId || !followingUserId) {
          throw new Error("用户ID或作者ID缺失");
        }

        if (this.isFollowing) {
          // 取消关注 - 同时调用两个接口
          const [unfollowFollowingRes, unfollowFollowerRes] = await Promise.all(
            [
              // 使用params传递查询参数
              this.$axios.post(`/following/unfollow`, null, {
                params: { userId, followingUserId },
              }),
              // 使用路径变量
              this.$axios.post(
                `/follower/unfollow/${followingUserId}/${userId}`
              ),
            ]
          );

          if (
            unfollowFollowingRes.data.code === 200 &&
            unfollowFollowerRes.data.code === 200
          ) {
            // 更新本地状态
            this.isFollowing = false;
            this.author.followerCount = Math.max(
              0,
              (this.author.followerCount || 0) - 1
            );

            // 更新用户信息（可选）
            this.$store.commit("updateUserFollowingCount", -1);

            this.$message.success("取消关注成功");
          } else {
            throw new Error(
              unfollowFollowingRes.data.message ||
                unfollowFollowerRes.data.message ||
                "取消关注失败"
            );
          }
        } else {
          // 关注作者 - 同时调用两个接口
          const [followFollowingRes, followFollowerRes] = await Promise.all([
            // 使用params传递查询参数
            this.$axios.post(`/following/follow`, null, {
              params: { userId, followingUserId },
            }),
            // 使用路径变量
            this.$axios.post(`/follower/follow/${followingUserId}/${userId}`),
          ]);

          if (
            followFollowingRes.data.code === 200 &&
            followFollowerRes.data.code === 200
          ) {
            // 更新本地状态
            this.isFollowing = true;
            this.author.followerCount = (this.author.followerCount || 0) + 1;

            // 更新用户信息（可选）
            this.$store.commit("updateUserFollowingCount", 1);

            this.$message.success("关注成功");
          } else {
            throw new Error(
              followFollowingRes.data.message ||
                followFollowerRes.data.message ||
                "关注失败"
            );
          }
        }
      } catch (error) {
        console.error("操作失败", error);
        this.$message.error(error.message || "操作失败，请稍后重试");
      } finally {
        this.loading = false;
      }
    },
    editArticle() {
      this.$router.push(`/writeArticle/${this.article.id}`);
    },
  },
};
</script>

<style scoped>
/* 样式部分保持不变 */
.view-article-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  position: relative;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
  width: 100%;
}

.bg-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  overflow: hidden;
}

.bg-dot {
  position: absolute;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #ffb76b, #ff7c00);
  opacity: 0.1;
  animation: float 6s infinite ease-in-out;
  filter: blur(2px);
}

.dot-2 {
  right: 10%;
  bottom: 15%;
  width: 80px;
  height: 80px;
  animation-delay: -2s;
  animation-duration: 8s;
}

.dot-3 {
  left: 20%;
  top: 70%;
  width: 100px;
  height: 100px;
  animation-delay: -3s;
  animation-duration: 10s;
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0) rotate(0deg);
  }
  50% {
    transform: translateY(-30px) rotate(5deg);
  }
}

.article-info {
  display: flex;
  justify-content: space-between;
  width: 80%;
  max-width: 800px;
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(5px);
  border-radius: 20px;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08);
  padding: 25px;
  margin-bottom: 20px;
}

.info-left {
  flex: 3;
}

.info-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.user-avatar-small {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-bottom: 10px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  border: 3px solid white;
  transition: transform 0.3s;
}

.user-avatar-small:hover {
  transform: rotate(10deg);
}

.article-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  font-size: 12px;
  color: #909399;
  margin-bottom: 15px;
}

.article-meta i {
  margin-right: 5px;
}

.article-introduction {
  font-size: 14px;
  color: #606266;
  margin-bottom: 15px;
  line-height: 1.6;
}

.article-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 20px;
}

.article-tags .tag {
  padding: 4px 10px;
  border-radius: 12px;
  background: rgba(255, 183, 107, 0.1);
  font-size: 12px;
  color: #ff7c00;
}

.follow-button,
.edit-button {
  text-align: center;
  width: 100%;
}

.follow-button button,
.edit-button button {
  border-radius: 24px;
  background: linear-gradient(135deg, #ffb76b, #ff7c00);
  border: none;
  height: 36px;
  font-size: 14px;
  padding: 0 20px;
  transition: all 0.3s;
  box-shadow: 0 5px 15px rgba(255, 183, 107, 0.3);
  color: white;
  width: 100%;
}

.follow-button button:hover,
.edit-button button:hover {
  background: linear-gradient(135deg, #ff9d34, #ff6a00);
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(255, 157, 52, 0.4);
}

.article-content {
  width: 80%;
  max-width: 800px;
}
</style>